package org.xmx0632.connector.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.util.StringUtils;
import org.xmx0632.connector.protocol.message.Message;
import org.xmx0632.connector.protocol.processor.MessageProcessor;

public class SpringContextHolder {
	private static final Logger LOG = LoggerFactory.getLogger(SpringContextHolder.class);

	private static final String MESSAGE_PROCESSOR_POSTFIX = "Processor";

	private static AbstractApplicationContext ctx = null;

	public static void init(AbstractApplicationContext ctx) {
		SpringContextHolder.ctx = ctx;
	}

	public static Object getBean(String name) {
		try {
			LOG.debug("getBean:{}", name);
			return ctx.getBean(name);
		} catch (BeansException e) {
			LOG.error(e.getMessage(), e);
		}
		LOG.error("message handler [{}] not found. use default defaultMessageHandler.", name);
		return ctx.getBean("defaultMessageHandler");
	}

	@SuppressWarnings({ "rawtypes" })
	public static MessageProcessor getMessageProcessor( Message msg) {
		String clazzName = msg.getClass().getSimpleName();
		String handlerName = StringUtils.uncapitalize(clazzName) + MESSAGE_PROCESSOR_POSTFIX;
		MessageProcessor messageHandler = (MessageProcessor) SpringContextHolder.getBean(handlerName);
		return messageHandler;
	}

}
